<?PHP
/**
 * 核销人登录控制器
 */
namespace app\home\controller;

use think\Controller;
use think\Request;
use think\Db;
class LoginController extends Controller{
    public $param = null;
    public function __construct(){
        parent::__construct();
        $userinfo = session('userinfo');
        if(!empty($userinfo)){
            echo json_encode(['code'=>100,'msg'=>'用户已登录','data'=>$userinfo]);
            die;
        }
        $this->param = Request::instance()->param('','','u_trim');
        // $this->param = Request::instance()->param();
    }
    /**
     * 核销员登录
     * @return [type] [description]
     */
    public function index(){
        $param = $this->param;
        $username = isset($param['username']) ? :'';
        $password = isset($param['password']) ? :'';
        // die;
        // $data['user_name'] = request()->post('username','','u_trim');   
        // $data['user_pwd'] = request()->post('password','','u_trim');
        if(empty($username)) return json (['code'=>0,'msg'=>'请输入用户名','data'=>[]]);   
        if(empty($password)) return json (['code'=>0,'msg'=>'请输入密码','data'=>[]]);
        $db = db();    
        #判断用户是否存在且是否为店铺或绑定的有店铺 并且店铺为健身类
        $user = $db->table('fanwe_user')->where(['user_name|mobile'=>$username])->find();
        if(empty($user)) return json ([['code'=>-1,'msg'=>'用户信息不存在','data'=>[]]]);
        if($user['user_pwd'] != md5($password)) return json ([['code'=>0,'msg'=>'密码不正确','data'=>[]]]);
        if($user['is_effect'] !=1 || $user['is_delete'] != 0) return json ([['code'=>0,'msg'=>'账户被禁用或已删除','data'=>[]]]);
        $sql = 'select a.user_id,a.supplier_id,a.is_delete,a.is_main,s.name as supplier_name,s.preview,s.address,s.user_id as supplier_userid,s.type from fanwe_supplier_account as a inner join fanwe_supplier as s on s.id = a.supplier_id where a.user_id = '.$user['id'].' limit 0,1';
        $seller = $db->query($sql);
        if(empty($seller)) return json ([['code'=>0,'msg'=>'请使用商户账户或子账户登录','data'=>[]]);
        $seller = $seller[0];
//        $seller = $db->table('fanwe_supplier_account')->field('a.user_id,a.supplier_id,a.is_delete,a.is_main,s.name as supplier_name,s.preview,s.address,s.user_id as supplier_userid,s.type')->alias('a')->join('fanwe_supplier as s ',' s.id = a.supplier_id')->where(['a.user_id'=>$user['id']])->find();
        $seller['user_name'] = $user['user_name'];   $seller['mobile'] = $user['mobile'];
        $seller['is_effect'] = $user['is_effect'];   $seller['is_delete'] = $user['is_delete'];
        $seller['uniqid'] = $user['uniqid'];    $seller['preview'] = 'http://chwl.homebank.shop'.substr($seller['preview'],1);
        $seller['user_id'] = $user['user_id'];
        session('userinfo',$seller);
        return json(['code'=>1,'msg'=>'登录成功','data'=>$seller]);
    }

    /**
     * 退出登录
     * @return [type] [description]
     */
    public function logout(){
        session('userinfo',null);
        return json(['code'=>1,'msg'=>'退出成功']);
    }
}